<template>
  <div class="edu-page-warp inquiryResults">
    <div class="" v-if="!this.global.isStudent">
      <condition-card @reset="reset" @search="searchList" label-width="110px" label-position="right">
        <el-row style="height: 50px;">
          <!-- :gutter="24" -->
          <el-col :span="8">
            <el-form-item :label="$t('administrationClass.grade')">
              <el-date-picker class="search-item" :clearable="false" v-model="queryForm.condition.grade" @change="handleGradeChange" value-format="yyyy" type="year" :placeholder="$t('graduationDesign.pleaseChoose')" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('administrationClass.college')">
              <el-select v-model="queryForm.condition.college" @change="collegeChange" clearable filterable style="width:100%">
                <el-option v-for="item in options.college" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('administrationClass.major')">
              <el-select v-model="queryForm.condition.major" clearable filterable style="width:100%">
                <el-option v-for="item in options.major" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="理论分数">
              <el-col :span="11">
                <el-form-item prop="minTheoryScore">
                  <el-input v-model="queryForm.condition.minTheoryScore" type="number" min=0 placeholder="请输入" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item prop="maxTheoryScore">
                  <el-input v-model="queryForm.condition.maxTheoryScore" type="number" min=0 placeholder="请输入" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实践环节学时">
              <el-col :span="11">
                <el-form-item prop="minHour">
                  <el-input v-model="queryForm.condition.minHour" type="number" min=0 placeholder="请输入" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-form-item prop="maxHour">
                  <el-input v-model="queryForm.condition.maxHour" type="number" min=0 placeholder="请输入" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最终成绩">
              <el-select v-model="queryForm.condition.finalResult"  clearable filterable style="width:100%">
                <el-option v-for="item in optionFinallist" :key="item.scoreNum" :label="item.scoreName" :value="item.scoreNum">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
      <el-card shadow="never">
        <div class="edu-page-title seachlaseach clearfix">
          <span class="fl">社会实践课成绩查询</span>
          <span class="seachenter fr">*实践环节要求在3学年完成{{parseFloat(ruleForm.necessaryHour)+parseFloat(ruleForm.electiveHour)?parseFloat(ruleForm.necessaryHour)+parseFloat(ruleForm.electiveHour):0}}学时,包括{{ruleForm.necessaryHour?ruleForm.necessaryHour:0}}学时必修和{{ruleForm.electiveHour?ruleForm.electiveHour:0}}学时选修</span>
        </div>
        <div class="edu-opertion-bar">
          <div class="float-left">
            <KeywordInput v-model="queryForm.condition.name" @enter="searchList" placeholder="请输入学号或姓名搜索"></KeywordInput>
          </div>
          <div class="float-right">
            <el-button @click="onExport">{{$t('message.export')}}</el-button>
          </div>
        </div>
        <el-table :order="false" :selection="true" @selection-change="handleSelectionChange" :data="labourList">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column :label="$t('examinInquiry.studentNumber')" prop="studentId" fixed="left" min-width="80" />
          <el-table-column :label="$t('examinInquiry.fullName')" prop="name" min-width="80" />
          <el-table-column :label="$t('examinInquiry.grade')" prop="grade" min-width="70" />
          <el-table-column :label="$t('examinInquiry.college')" prop="collegeI18n" min-width="140" show-overflow-tooltip />
          <el-table-column :label="$t('examinInquiry.major')" prop="majorI18n" :render-header="labelHead" show-overflow-tooltip min-width="140" />
          <el-table-column label="理论分数" prop="theoryScore" min-width="80" />
          <el-table-column label="实践环节完成情况 (认定学时)" prop="score" :render-header="labelHead" show-overflow-tooltip min-width="260">
            <template slot-scope="scope">
              必修 <span class="necessaryClass">{{scope.row.necessaryHour?scope.row.necessaryHour:0}}</span> 学时,选修 <span class="electiveClass">{{scope.row.electiveHour?scope.row.electiveHour:0}}</span> 学时   总学时 {{parseFloat(scope.row.necessaryHour?scope.row.necessaryHour:0)+parseFloat(scope.row.electiveHour?scope.row.electiveHour:0)}}
            </template>
          </el-table-column>
          <el-table-column label="最终成绩" prop="finalResult" :render-header="labelHead" show-overflow-tooltip min-width="80" />
          <el-table-column :label="$t('message.operating')" fixed="right" width="100">
            <template slot-scope="scope">
              <div>
                <el-button type="text" @click.stop="handleClick(scope.row)" size="mini">查看明细</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="edu-pagination">
          <div class="float-right">
            <el-pagination :current-page="pageNum_" :page-sizes="[10,20, 50, 100, 500, 1000]" :page-size="pageSize_" :total="total_" layout="total, sizes, prev, pager, next, jumper" style="float: right;margin:10px 60px 0 0;" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </div>
      </el-card>
      <!-- 弹框 -->
      <el-dialog class="queryFinaClass" title="" width="70%" :visible.sync="updateDialog" :auto-height="true">
        <div>
          <div class="edu-page-title laseach clearfix">
            <span class="oneSpan fl">{{rows.studentId}}{{rows.name}} 实践环节学时明细</span>
            <span class="laseachClass fr">*实践环节要求在3学年完成{{parseFloat(ruleForm.necessaryHour)+parseFloat(ruleForm.electiveHour)?parseFloat(ruleForm.necessaryHour)+parseFloat(ruleForm.electiveHour):0}}学时,包括{{ruleForm.necessaryHour?ruleForm.necessaryHour:0}}学时必修和{{ruleForm.electiveHour?ruleForm.electiveHour:0}}学时选修</span>
          </div>
          <el-table :data="queryFinalList">
            <el-table-column label="板块" prop="plateName" width="160" show-overflow-tooltip>
              <template slot-scope="scope">
                <span :class="scope.row.nature=='1'?'red':''">{{scope.row.nature=='1'?'*':''}}{{scope.row.plateName}}</span>
              </template>
            </el-table-column>
            <el-table-column label="项目性质" prop="nature" width="80">
              <template slot-scope="scope">
                <span :class="scope.row.nature=='1'?'red':''">{{scope.row.nature=='1'?'必修':'选修'}}</span>
              </template>
            </el-table-column>
            <el-table-column label="录入学时" prop="hour" width="80" />
            <el-table-column label="认定学时" prop="paramHour" width="80" />
            <el-table-column label="参与次数" prop="count" width="80" />
            <el-table-column label="学年学期" prop="calendarId" width="180" />  
            <el-table-column label="项目名称" prop="name" :render-header="labelHead" show-overflow-tooltip  />
            <el-table-column label="活动日期" prop="activityDate" :render-header="labelHead"  width="110" />
          </el-table>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="updateDialog = false">关 闭</el-button>
        </span>
      </el-dialog>
    </div>
    <div v-if="this.global.isStudent" class="queryFinaClass2">
      <el-card shadow="never">
        <div class="edu-page-title">学生查询社会实践课成绩</div>
        <el-row class="deRow">
          <el-col :span="8">
            理论学习<br>
            <span>{{this.theorylist&&this.theorylist.length>0?'完成':'未完成'}}</span>
          </el-col>
          <el-col :span="8">
            实践环节（必修）<br>
            <span>{{!necessaryHourTip?'未完成':'完成'}}</span>
          </el-col>
          <el-col :span="8">
            实践环节（选修）<br>
            <span>{{electiveHourTip?'完成':'未完成'}}</span>
          </el-col>
        </el-row>
        <div class="edupage clearfix">
          <span class="fl">实践环节明细</span>
          <span class="laseachClass fr">*实践环节要求在3学年完成{{parseFloat(ruleForm.necessaryHour)+parseFloat(ruleForm.electiveHour)?parseFloat(ruleForm.necessaryHour)+parseFloat(ruleForm.electiveHour):0}}学时,包括{{ruleForm.necessaryHour?ruleForm.necessaryHour:0}}学时必修和{{ruleForm.electiveHour?ruleForm.electiveHour:0}}学时选修</span>
        </div>
        <el-table :data="queryFinalList">
          <el-table-column label="板块" prop="plateName" >
            <template slot-scope="scope">
              <span :class="scope.row.nature=='1'?'red':''">{{scope.row.nature=='1'?'*':''}}{{scope.row.plateName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="项目性质" prop="type" >
            <template slot-scope="scope">
              <span :class="scope.row.nature=='1'?'red':''">{{scope.row.nature=='1'?'必修':'选修'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="实际学时" prop="hour"  />
          <el-table-column label="认定学时" prop="paramHour"  />
        </el-table>
      </el-card>
    </div>
  </div>

</template>
<script>
import api from 'common/src/api/score/bachelor/labourCourse';
import tools from 'common/src/views/underGraduationDesign/tools.js';
import { queryDic } from "common/src/api/dictionary";
import { mapState } from 'vuex'
import {
  selectStudentInfoByStuId,
} from "common/src/api/culture/change";
import UTILS from "common/src/utils/utils";
import mixin from 'common/src/mixins/index';
const defaultCreateForm = {
  studentId: null,
  studentName: null,
  professionI18n: null,
  grade: '',
  score: ''
};

// 院聘导师库
export default {
  name: "",
  mixins: [mixin],
  components: {

  },
  computed: {
    ...mapState({
      mockUser: state => state.session.mockUser
    })
  },
  created() {
  },
  mounted() {
    this.getOptions();//列表
    this.Scorelist();//学院
    this.optionFinallistfun();//最终成绩
    //参数配置
    this.LaborEducationList().then(()=>{
      if (this.global.isStudent) {
        if (this.mockUser.uid) {
          this.TheoryDetails(this.mockUser.uid, true);
          this.theory();//理论分数是否完成
        }
      }
    })
  },
  watch: {
  },
  data() {
    return {
      updateDialog: false,
      dialogTitle: '',
      multipleSelection: [],
      labourList: [],
      queryFinalList: [],
      theorylist: [],
      necessaryHourTip: true,
      electiveHourTip: false,
      arrNatrue: [],
      mode: '',
      tip: 2,
      btnTip: false,
      rows: {
        studentId: '',
        name: ''
      },
      // String(new Date().getFullYear())
      queryForm: {
        pageNum_: 1,
        pageSize_: 10,
        condition: {
          grade: String(new Date().getFullYear()), // 年级
          college: '', // 学院
          major: '', // 专业
          minTheoryScore: null,
          maxTheoryScore: null,
          minHour: null,
          maxHour: null,
          page: true,
          name: ''
        }
      },
      queryForm2: {
        pageNum_: 1,
        pageSize_: 10,
        condition: {
          grade: '', // 年级
          college: '', // 学院
          major: '', // 专业
          min: null,
          max: null,
          page: true,
          studentName: ''
        }
      },
      ruleForm: {
        necessaryHour: '',
        electiveHour: ''
      },
      options: {
        college: [],
        major: []
      },
      optionFinallist: [],//最终成绩
      queryParams: {

      },
      message: '',
      createForm: UTILS.clone(defaultCreateForm),
      paramList:[]
    };
  },
  methods: {
    searchList() {
      if (parseFloat(this.queryForm.condition.minTheoryScore) > parseFloat(this.queryForm.condition.maxTheoryScore)) {
        this.$message('理论分数最小数不可大于最大数');
        return
      }
      if (parseFloat(this.queryForm.condition.minHour) > parseFloat(this.queryForm.condition.maxHour)) {
        this.$message('实践环节学时最小数不可大于最大数');
        return
      }
      this.Scorelist();
    },
    // 最终成绩
    optionFinallistfun() {
      var obj = {
        "page": 1,
        "pageSize": 20,
        "projectId": 1,
        "coretypeCode": 3
      }
      api.optionFinallistapi(obj).then(res => {
        if (res.code === 200) {
          this.optionFinallist = res.data.list[0].scoreDetail;
        }
      });
    },
    LaborEducationList() {
      return api.LaborEducation().then(res => {
        if (res.code === 200) {
          this.paramList = res.data;
          this.LaEducaDate = res.data.filter(item => item.id != 1);//板块
          var numTotal = 0;
          this.LaEducaDate.forEach((item, index) => {
            if (item.nature != 1) {
              numTotal += item.electiveHour;
            }
          })
          this.codeList = res.data.filter(item => item.id == 1);//课程代码
          if (this.codeList[0]) {
            this.ruleForm = this.codeList[0];
          }
        }
      });
    },
    theory() {
      if (this.mockUser.uid) {
        this.queryForm2.condition.studentName = this.mockUser.uid;
      }
      api.labourTheoryScorelist(this.queryForm2).then(res => {
        if (res.code === 200) {
          this.theorylist = res.data.list;
        }
      });
    },
    // 筛选条件字典查询
    Scorelist() {
      api.queryFinalResultlist(this.queryForm).then(res => {
        if (res.code === 200) {
          this.labourList = res.data.list;
          this.total_ = res.data.total_;
        }
      });
    },
    // 重置筛选框
    reset() {
      this.queryForm = {
        pageNum_: 1,
        pageSize_: 10,
        condition: {
          grade: String(new Date().getFullYear()), // 年级
          college: '', // 学院
          major: '', // 专业
          min: null,
          max: null,
          page: true,
          name: ''
        }
      }
      this.searchList()
      //清空专业
      this.options.major=[]
      this.queryForm.condition.major=null
    },
    //新增 输入学号带入学生信息
    focusFun(val) {
      selectStudentInfoByStuId(this.createForm.studentId).then(res => {
        if (res.code === 200) {
          if (res.data[0] && res.data.length > 0) {
            this.btnTip = false;
            this.createForm = res.data[0];
            this.createForm.majorI18n = res.data[0].professionI18n;
          } else if (res.data.length == 0) {
            if (this.createForm.studentId) {
              this.btnTip = true;
              this.$message('此学号不存在');
              return
            }
          }
        }
      }).catch(e => {
        // reject(e);
      })
    },
    //查看明细
    handleClick(rows) {
      this.updateDialog = true;
      this.rows = rows;
      if (rows.studentId) {
        this.TheoryDetails(rows.studentId);
      }
    },
    //详情
    TheoryDetails(studentId, isStudent = false) {
      api.queryFinalDetail(studentId).then(res => {
        if (res.code === 200) {
          //关联认定学分
          res.data.forEach(row => {
            let param = this.paramList.find(param=>param.id == row.plateId)
            row.paramHour = param? param.necessaryHour:null
          });
          //当前为学生时，汇总各个板块学分
          if(isStudent){
              let newArr=[];
              res.data.forEach(row => {
                let item = newArr.find(item => item.plateId === row.plateId)
                if(item){
                  item.hour+=row.hour;
                }else{
                  newArr.push({
                    plateId:row.plateId,
                    plateName:row.plateName,
                    nature:row.nature,
                    hour:row.hour,
                    paramHour:row.paramHour
                  })
                }
              })
              this.queryFinalList = newArr;
          }else{
            this.queryFinalList = res.data;
          }
          this.queryFinalList.forEach(item => {
            let recordHour = parseFloat(item.hour);
            let realHour =parseFloat(item.paramHour);
            if(recordHour<realHour){
              item.paramHour=item.hour;
            }
            item.paramHour=Number(item.paramHour);
          })
          //必修----有一个模块不满足就是未完成
          var arr1 = res.data.filter(item => item.nature == 1);
          this.arrNatrue = arr1;
          let result = {};
          if (arr1 && arr1.length > 0) {
            arr1.forEach((item, index) => {
              if (result[item.plateId]) {
                result[item.plateId] += item.hour;
              } else {
                result[item.plateId] = item.hour;
              }
            })
            let sArr = [];
            for (let k in result) {
              sArr.push({ plateId: k, hour: result[k] });
            }
            sArr.forEach((item, index) => {
              this.LaEducaDate.forEach((item2, index2) => {
                if (parseFloat(item.plateId) == parseFloat(item2.id)) {
                  if (parseFloat(item.hour) < parseFloat(item2.necessaryHour)) {
                    this.necessaryHourTip = false;//必修未完成
                  }
                }
              })
            })
          } else {
            this.necessaryHourTip = false;
          }

          //选修----总和大于选修分数即完成
          var arr2 = res.data.filter(item => item.nature != 1);
          var ntol = 0;
          if (arr2 && arr2.length > 0) {
            arr2.forEach((item, index) => {
              ntol += item.hour;
            })
            if (parseFloat(ntol) >= parseFloat(this.ruleForm.electiveHour)) {
              this.electiveHourTip = true;//选修完成
            }
          } else {
            this.electiveHourTip = false;
          }

        }
      });
    },
    //添加保存
    submitForm() {
      this.$refs.createForm.validate(valid => {
        if (valid) {
          if (this.mode == 'ADD') {
            let data = {
              studentId: this.createForm.studentId,
              score: this.createForm.score
            }
            api.labourTheoryScoreAdd(data).then(res => {
              if (res.code === 200) {
                this.$refs.updateDialog.close();
                this.searchList()
              }
            });
          } else if (this.mode == 'EDIT') {
            let data = {
              id: this.rows.id,
              studentId: this.createForm.studentId,
              score: this.createForm.score
            }
            api.labourTheoryScoreedit(data).then(res => {
              if (res.code === 200) {
                this.$refs.updateDialog.close();
                this.searchList()
              }
            });
          }

        }
      });
    },
    handleGradeChange() {
      this.options.major=[];
      this.queryForm.condition.major=null;
      if(this.queryForm.condition.college){
        this.collegeChange(this.queryForm.condition.college);
      }
    },
    // 筛选条件字典查询
    getOptions() {
      if(this.global.isAnyTeacher){
        this.options.college.push({
            label:this.global.currentUser.facultyName,
            value:this.global.currentUser.faculty,
        })
        return
      }
      let data = {
        lang: this.$store.getters.language || 'cn',
        type: 'allChild',
        keys: ['X_YX']
      }
      queryDic(data).then(res => {
          UTILS.fillSelect({ college: 'X_YX' }, res.data, this.options)
          if(this.global.isAcdemicDean){
              if(this.global.currentUser.manageFaculty !== null && this.global.currentUser.manageFaculty !==''){
                  let manageFaculty = this.global.currentUser.manageFaculty.split(',')
                  this.options.college=this.options.college.filter(item=>manageFaculty.includes(item.value))
              }else{
                  this.options.college=[{label:this.global.currentUser.facultyName,value:this.global.currentUser.faculty}]
              }
          }
      })
    },
    // 修改学院
    collegeChange(val) {
      this.options.major = []
      this.queryForm.condition.major = ''
      let data = {
        lang: this.$store.getters.language || 'cn',
        type: 'allChild',
        keys: ['G_ZY'],
        filter: {
          grade: this.queryForm.condition.grade,
          prefix: [val],
          specilaCode: 'XY2ZY',
          facultys: [val]
        }
      }
      queryDic(data).then(res => {
        UTILS.fillSelect(
          {
            major: 'G_ZY' // 专业
          },
          res.data,
          this.options
        )
      })
    },
    close(data) {
      if (data.id) {//编辑
        this.closeDialog();
      } else {
        this.$refs.updateDialog.close();
      }
    },
    closeDialog() {
      this.$refs.updateDialog.close();
      this.$refs.createForm.clearValidate();
    },
    resetAddForm() {
      this.$refs.createForm.clearValidate();
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 分页
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val
      this.searchList(this.queryForm)
    },
    // 分页
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val
      this.queryForm.pageNum_ = 1
      this.searchList(this.queryForm)
    },
    // 导出
    onExport() {
      let data = _.cloneDeep(this.queryForm.condition);
      if(this.multipleSelection && this.multipleSelection.length > 0){
        data.studentIds = this.multipleSelection.map(item => item.studentId)
      }
      api.exportqueryFinal(data).then(res => {
        if (res.code == 200) {
          tools.downloadFile(res.data.key, "社会实践课成绩.xls", null, this);
        }
      })
    }
  }
};
</script>
<style lang="scss" scoped>
.red {
    color: red;
}
.edu-page-title {
    margin-bottom: 22px;
}
.line {
    text-align: center;
}
.deRow {
    margin-bottom: 15px;
}
.deRow .el-col {
    text-align: center;
    line-height: 30px;
    margin: 0 0 20px 0;
}
.deRow .el-col span {
    font-size: 24px;
}
.edupage {
    height: auto;
    font-weight: bold;
    margin-bottom: 20px;
    font-family: PingFangSC-Medium;
    font-size: 18px;
    color: #2b3b4e;
    letter-spacing: 0;
    line-height: 20px;
}
.laseach .oneSpan {
    font-size: 14px;
}
.seachlaseach .seachenter {
    font-size: 12px;
}
.necessaryClass{
  color:red;
}
.electiveClass{
  color: dodgerblue;
}
</style>
<style>
.clearfix {
    display: block;
    clear: both;
    content: '';
}
.fl {
    float: left;
}
.fr {
    float: right;
}
.queryFinaClass .el-dialog__header {
    border-bottom: none !important;
    padding: 0 24px !important;
}
.queryFinaClass .el-dialog__headerbtn {
    top: 7px !important;
}
.queryFinaClass2 .el-dialog__title,
.queryFinaClass2 .edupage {
    font-size: 16px !important;
}
.queryFinaClass2 .laseachClass,
.queryFinaClass .laseachClass {
    font-size: 12px !important;
}
.queryFinaClass2 .el-dialog__header {
    border-bottom: none !important;
    padding: 18px 24px !important;
}
.queryFinaClass2 .el-dialog__headerbtn {
    top: 7px !important;
}
.queryFinaClass2 .el-dialog__body {
    padding-top: 7px !important;
}
.queryFinaClass2 .el-card__body {
    padding-bottom: 60px !important;
}
.queryFinaClass2 .deRow {
    margin-bottom: 13px !important;
}
.inquiryResults .queryFinaClass .el-dialog__footer {
    border-top: none !important;
}
.inquiryResults .queryFinaClass .el-dialog__body {
    padding-bottom: 10px !important;
}
</style>
